
<template>
  <div
      class="drag-container"
      :class="{drag: canDrag}"
      @mousedown="mousedown"
      @dblclick="positionClear"
      ref="dragContainer"
      :style="{position:limit?'absolute':'fixed'}">

    <slot></slot>
  </div>
</template>
<script >

export default {
  name: "Drag",
  props: {
    canDrag: {
      type: Boolean,
      default: true
    },
    limit: { //默认true相对父级拖动， false相对window拖动
      type: Boolean,
      default: true
    },
    dragId: { //指定拖拽id
      type: String,
      default: ''
    }
  },
  data() {
    return {
      copyStyle: {},
      isMousedown: false,
      startLeft: 0,
      startTop: 0,
      nowLeft: 0,
      nowTop: 0,
      el: null
    }
  },
  methods: {
    mousedown(e) {
      if (!this.canDrag) {
        return
      }
      if (this.dragId) { //如果指定了拖拽id
        if (e.target != document.getElementById(this.dragId)) {
          return
        }
      }
      const vm = this
      let disX = e.clientX - vm.el.offsetLeft
      let disY = e.clientY - vm.el.offsetTop

      document.onmousemove = ev => {
        let left = ev.clientX - disX
        let top = ev.clientY - disY
        let parentWidth = this.limit ? vm.el.parentNode.offsetWidth : document.body.offsetWidth
        let parentHeight = this.limit ? vm.el.parentNode.offsetHeight : document.body.offsetHeight
        //上下左右上下限制 预留20px
        left = left <= -vm.el.offsetWidth + 20 ? -vm.el.offsetWidth + 20 : left
        top = top <= -vm.el.offsetHeight + 20 ? -vm.el.offsetHeight + 20 : top

        left = left >= parentWidth - 20 ? parentWidth - 20 : left
        top = top >= parentHeight - 20 ? parentHeight - 20 : top

        vm.el.style.left = left + 'px'
        vm.el.style.top = top + 'px'
      }
      document.onmouseup = () => {
        document.onmousemove = null
        document.onmouseup = null
      }
    },
    positionClear() {
      this.el.style.left = this.startLeft + 'px'
      this.el.style.top = this.startTop + 'px'
    }
    },
  mounted() {
    setTimeout(() => {
      this.el = this.$refs.dragContainer
      this.startLeft = this.nowLeft = this.el.offsetLeft || getComputedStyle(this.el).left
      this.startTop = this.nowTop = this.el.offsetTop || getComputedStyle(this.el).top
    }, 0)
  },
}
</script>

<style lang="scss" scoped>
.drag-container {
  // background-color: #fff;
  background-color: transparent;
  position: absolute;
  box-sizing: border-box;
  z-index: 99;
}
.drag {
  user-select: none;
}

</style>
